package com.web;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.domain.Users;
import com.service.Impl.UsersServiceImpl;
import com.service.UsersService;

@WebServlet("/loginServlet")
public class loginServlet extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
        //获取登录框数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(username);
        System.out.println(password);
        //判断用户名和对应的密码是否正确
        UsersService  usersService = new UsersServiceImpl();
        List<Users> list = usersService.findUser();
        for(int i = 0;i < list.size();i++) {
            System.out.println(list.get(i));
            //1.判断用户名是否存在于库中
            if(username.equals(list.get(i).getUsername())){
                //存在
                System.out.println("进来了");
                //获取登录用户存在库中的信息
                Users user = usersService.findUserName(username);
                System.out.println(user);
                //判断密码是否正确
                if(password.equals(user.getPassword())) {
                    System.out.println("判断密码");
                    //密码正确跳转首页面
                    //1.向域中存储信息
                    HttpSession session = request.getSession();
                    session.setAttribute("username", username);
                    response.sendRedirect("/woniusales/indexServlet");
                    return;
                }else {
                    request.setAttribute("message", "温馨提示：用户名或密码错误！");
                    request.getRequestDispatcher("/page/login1.jsp").forward(request, response);
                    return;
                }
            }else {
                System.out.println("不存在，跳转登录页面");
                //如果不存在
                if(i == list.size()-1) {
                    request.setAttribute("message", "温馨提示：您还未注册账号~请点击立即注册！");
                    request.getRequestDispatcher("/page/login1.jsp").forward(request, response);
                }
            }
        }


    }
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}
}
